package com.xingkeduo.business.order.domain;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xingkeduo.business.order.remote.AdminRemoteService;
import com.xingkeduo.business.order.remote.StoreRemoteService;
import com.xingkeduo.business.order.remote.feign.CommentFeignService;
import com.xingkeduo.business.order.remote.feign.StoreFeignService;
import com.xingkeduo.dto.CraftsmanDTO;
import com.xingkeduo.dto.ManagerTable;
import com.xingkeduo.dto.StoreRemoteDto;
import com.xingkeduo.dto.param.CutomerParam;
import com.xingkeduo.dto.param.CutomerQueryDto;
import com.xingkeduo.pojo.query.CustomerServiceMapper;
import com.xingkeduo.pojo.table.CustomerService;
import com.xingkeduo.util.pojo.exception.BusinessException;
import com.xingkeduo.utils.DateTimeUtils;
import com.xingkeduo.utils.PageResponseDTO;
import com.xingkeduo.utils.ResponseUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program xingkeduo_business_order
 * @description: 客户回访记录
 * @author: ch
 * @create: 2019/07/09 16:49
 */
@Service
public class CutomerQueyService {
    @Resource
    private CustomerServiceMapper customerServiceMapper;

    @Resource
    private StoreRemoteService storeRemoteService;

    @Resource
    private AdminRemoteService adminRemoteService;

    @Resource
    private StoreFeignService storeFeignService;

    @Resource
    private CommentFeignService commentFeignService;


    public String updateCutomer(CutomerParam cutomerParam) {
        CustomerService customerService = customerServiceMapper.selectById(cutomerParam.getId());
        if(customerService==null){
            throw new BusinessException(BusinessException.Type.DEFAULT, "该条数据不存在或id错误");
        }
        BeanUtils.copyProperties(cutomerParam, customerService);
        customerServiceMapper.updateById(customerService);
        aftermarket(cutomerParam.getOrderNo());
        return String.valueOf(customerService.getId());
    }


    public String initCutomer(CutomerParam cutomerParam) {
        CustomerService customerService = new CustomerService();
        cutomerIsExits(cutomerParam);
        BeanUtils.copyProperties(cutomerParam, customerService);
        customerServiceMapper.insert(customerService);
        aftermarket(cutomerParam.getOrderNo());
        return String.valueOf(customerService.getId());
    }


    public void cutomerIsExits(CutomerParam cutomerParam) {
        if(StringUtils.isNotBlank(cutomerParam.getOrderNo())){
            Integer integer = customerServiceMapper.selectCount(new QueryWrapper<CustomerService>().lambda().in(CustomerService::getOrderNo, cutomerParam.getOrderNo()));
            if (integer > 0) {
                throw new BusinessException(BusinessException.Type.DEFAULT, "该订单售后记录已存在");
            }

        }
    }



    public PageResponseDTO selectListPage(CutomerQueryDto cutomerQueryDto) {
        IPage<CustomerService> page = new Page<>(cutomerQueryDto.getPageNo(), cutomerQueryDto.getPageSize());
        //构造查询参数
        LambdaQueryWrapper<CustomerService> queryWrapper = generateQuery(cutomerQueryDto);

        IPage<CustomerService> orderIPage = customerServiceMapper.selectPage(page, queryWrapper);

        List<CustomerService> records = orderIPage.getRecords();
        List<CustomerService> collect = records.stream().peek(this::complementInfo)
                .collect(Collectors.toList());
        PageResponseDTO<CustomerService> dtos = new PageResponseDTO<>(orderIPage, collect);
        return dtos;
    }


    public void complementInfo(CustomerService customerService){

        customerService.setSaleTypeName(customerService.getSaleType().getValue());
        customerService.setStatusName(customerService.getStatus().getValue());
        customerService.setComplainTypeName(customerService.getComplainType().getValue());
        customerService.setReasonName(customerService.getReason().getValue());


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", customerService.getUpdatedBy());
        ResponseUtils<ManagerTable> managerTableResponseUtils = storeFeignService.manager_id(jsonObject.toJSONString());
        if (managerTableResponseUtils != null && managerTableResponseUtils.success()) {
            ManagerTable data = managerTableResponseUtils.getData();
            customerService.setUpdateByName(data.getRealname());

        }

        //查询店铺最新信息
        StoreRemoteDto storeRemoteDto = storeRemoteService.getByStoreId(customerService.getStoreId());
        if (storeRemoteDto != null) {
            customerService.setStoreName(storeRemoteDto.getStoreName());
            customerService.setCityName(storeRemoteDto.getCityName());
        }

        if (StringUtils.isNotBlank(customerService.getAdminId())) {
            CraftsmanDTO admin = adminRemoteService.getAdmin(customerService.getAdminId());
            if (admin != null) {
                customerService.setAdminName(admin.getNickName());
            }
        }



    }


    private LambdaQueryWrapper<CustomerService> generateQuery(CutomerQueryDto query) {

        LambdaQueryWrapper<CustomerService> queryWrapper = new QueryWrapper<CustomerService>().lambda();


        if (StringUtils.isNotBlank(query.getOrderNo())) {
            queryWrapper.eq(CustomerService::getOrderNo, query.getOrderNo());
        }

        if (query.getId() >0 ) {
            queryWrapper.eq(CustomerService::getId, query.getId());
        }


        if (StringUtils.isNotBlank(query.getStoreId())) {
            queryWrapper.eq(CustomerService::getStoreId, query.getStoreId());
        }

        if (query.getSaleType() != null) {
            queryWrapper.eq(CustomerService::getSaleType, query.getSaleType());
        }

        if (query.getStatus() != null) {
            queryWrapper.eq(CustomerService::getStatus, query.getStatus());
        }

        if (StringUtils.isNotBlank(query.getUpdatedBy())) {
            queryWrapper.eq(CustomerService::getUpdatedBy, query.getUpdatedBy());
        }



        if (StringUtils.isNotBlank(query.getStartTime()) || StringUtils.isNotBlank(query.getEndTime())) {
            String timeStart = query.getStartTime();
            String timeEnd = query.getEndTime();

            if(StringUtils.isBlank(timeStart)){
                timeStart = "1991-03-29";
            }
            if(StringUtils.isBlank(timeEnd)){
                timeEnd = "2100-01-01";
            }
            queryWrapper.between(CustomerService::getCreatedTime, DateTimeUtils.yyyy_MM_dd(timeStart), DateTimeUtils.yyyy_MM_dd(timeEnd));
        }

        queryWrapper.orderByDesc(CustomerService::getCreatedTime);

        return queryWrapper;
    }


    public CustomerService query(){
        return  customerServiceMapper.selectById(1);
    }

    
    /**
    * @description: 获取订单的售后状态
    * @author: ch
    * @Param [orderNos]
    * @return java.util.List<java.lang.String>
    * @date: 2019-08-06 16:21
    **/
    public List<Object> cutomerList(String[] orderNos) {
     List<Object> list =  customerServiceMapper.selectObjs(new QueryWrapper<CustomerService>().select("order_no").lambda().in(CustomerService::getOrderNo, orderNos));
     return list;
    }


    public void aftermarket(String orderNo){
        if(StringUtils.isNotBlank(orderNo)){
            commentFeignService.aftermarket(orderNo);
        }
    }
}
